﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Workflows.Components.TextMining.Collapse
{
    public class EINComparer:IAttributeComparer
    {
        #region Implementation of IAttributeComparer

        /// <summary>
        /// specify either use code snippet or class
        /// </summary>
        public AttributeComparerType ComparerType
        {
            get { return AttributeComparerType.ClassComparer; }
        }

        public SqlDbType FieldDbType
        {
            get { return SqlDbType.VarChar; }
            set {  }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <param name="penalty"></param>
        /// <param name="unevenDistTableName"></param>
        /// <returns></returns>
        public double Compare(object value1, object value2, double penalty, SqlConnection conn, string unevenDistTableName)
        {
            if (value1 == null || value1 == DBNull.Value ||
                value2 == null || value2 == DBNull.Value)
                return 0;

            string ein_1 = value1.ToString();
            string ein_2 = value2.ToString();
            if (ein_1.ToLower() == ein_2.ToLower())
                return 1;

            if (ein_1.Length < 10 || ein_2.Length < 10)
                return 0;
            ein_1 = ein_1.Substring(0, 10);
            ein_2 = ein_2.Substring(0, 10);
            if (ein_1.ToLower() == ein_2.ToLower())
                return 0.99;
            else
                return penalty;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="values"></param>
        /// <param name="unevenDistTableName"></param>
        /// <returns></returns>
        public object Merge(List<object> values, SqlConnection conn, string unevenDistTableName)
        {
            object mode = null;
            int maxFreq = 0;
            Dictionary<object, int> freqs = new Dictionary<object, int>();
            foreach (object val in values)
            {
                if (val == null || val.ToString().Length == 0)
                    continue;

                if (freqs.ContainsKey(val))
                    freqs[val] = freqs[val] + 1;
                else
                    freqs.Add(val, 1);
            }
            foreach (object val in freqs.Keys)
            {
                if (freqs[val] > maxFreq)
                {
                    maxFreq = freqs[val];
                    mode = val;
                }
            }
            return mode;
        }

        #endregion
    }
}
